package com.manning.s2ip.actions;

import java.sql.ResultSet;
import java.sql.SQLException;
import java.util.HashMap;
import java.util.List;

import javax.sql.DataSource;

import org.apache.struts2.convention.annotation.Action;
import org.apache.struts2.convention.annotation.InterceptorRef;
import org.apache.struts2.convention.annotation.InterceptorRefs;
import org.apache.struts2.convention.annotation.Result;
import org.apache.struts2.convention.annotation.Results;
import org.springframework.jdbc.core.JdbcTemplate;
import org.springframework.jdbc.core.RowMapper;

import com.manning.s2ip.beans.Person;
import com.opensymphony.xwork2.ActionSupport;

@Results({
	@Result(name="list", type="json", params={"root","personList"}) 
})
@InterceptorRefs({
	@InterceptorRef("defaultStack"), 
	@InterceptorRef("dsLogger")
})
public class PersonAction extends ActionSupport {
	
	private JdbcTemplate jdbcTemplate;
	private HashMap<String,List<Person>> personList;
    
	@SuppressWarnings("unchecked")
	@Action("person-list")
    public String list() {
		List tempPersonList = this.jdbcTemplate.query(
				"SELECT * FROM people", 
				new RowMapper() {
			        public Object mapRow(ResultSet rs, int rowNum) throws SQLException {
			            Person person = new Person();
			            person.setId(rs.getInt("id"));
			            person.setName(rs.getString("name"));
			            person.setPostalCode(rs.getString("postalCode"));
			            person.setFavoriteColor(rs.getString("favoriteColor"));
			            return person;
			        }
				});
		personList = new HashMap<String,List<Person>>();
		personList.put("results", tempPersonList);
    	return "list";
    }
	
	public HashMap<String,List<Person>> getPersonList() {
		return personList;
	}
	
	public void setDataSource(DataSource dataSource ) {
		this.jdbcTemplate = new JdbcTemplate(dataSource);
	}

}
